package com.core.gwt.place.client;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.activity.shared.Activity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

/**
 * An abstract {@link Activity} class which enables breaking down the
 * implementation of complex activities into more manageable sub-activities,
 * each handling a specific area of the complex activity's view. All
 * sub-activities must handle the same place type as the parent activity. They
 * can be developed and tested independently and then assembled into the parent
 * (composite) activity. <br>
 * <br>
 * The extending classes must provide a panel (an {@link AcceptsOneWidget} ) for
 * each sub-activity in their views. They must start their sub-activities by
 * calling {@link #startSubActivity} from within their implementation of
 * {@link Activity#start}. From then on the life-cycle of the sub-activities
 * will be managed automatically.<br>
 * <br>
 * This class also provides management of {@link Mode}s through a built-in
 * {@link ModeManager}.
 * 

 */
public abstract class CompositeActivity extends AbstractActivity {

	private final SubActivityManager subActivityManager;

	protected CompositeActivity() {
		subActivityManager = new SubActivityManager();
	}

	@Override
	public String mayStop() {
		String result = super.mayStop();
		if (result == null) {
			result = subActivityManager.mayStop();
		}
		return result;
	}

	@Override
	public void onCancel() {
		super.onCancel();
		subActivityManager.onCancel();
	}

	@Override
	public void onStop() {
		super.onStop();
		subActivityManager.onStop();
	}

	/**
	 * Attaches a {@link Presenter} to its widget and adds it to the list of
	 * managed sub-activities.
	 * 
	 * @param <V>
	 *            the view type
	 * @param presenter
	 *            the presenter
	 * @param view
	 *            the widget
	 * @param eventBus
	 *            the event bus
	 */
	protected final <V> void attachPresenter(final Presenter<V> presenter,
			final V view, final EventBus eventBus) {
		subActivityManager.attach(presenter, view, eventBus);
	}

	/**
	 * Starts a sub-activity and adds it to the list of managed sub-activities.
	 * Call this method from your implementation of {@link Activity#start}.
	 * 
	 * @param activity
	 *            the sub-activity to start
	 * @param panel
	 *            an area of the composite activity's view in which the
	 *            sub-activity will display its own view
	 * @param eventBus
	 *            the event bus
	 */
	protected final void startSubActivity(final Activity activity,
			final AcceptsOneWidget panel, final EventBus eventBus) {
		subActivityManager.start(activity, panel, eventBus);
	}
}
